<template>
  <el-col :span="element.span" :class="className" @click.stop="activeItem(element)">
    <el-form-item
      v-if="element.layout === 'colFormItem'"
      :label="element.label"
      :label-width="element.labelWidth ? element.labelWidth + 'px' : null"
      :required="element.required"
    >
      <!-- 动态渲染组件 -->
      <component
        :is="getComponent(element.typeId)"
        v-bind="element"
        v-model="element.defaultValue"
        :props="element.vModel"
      />
    </el-form-item>
    <span class="drawing-item-copy" title="复制" @click.stop="copyItem(element)">
      <el-icon>
        <CopyDocument />
      </el-icon>
    </span>
    <span class="drawing-item-delete" title="删除" @click.stop="deleteItem(index)">
      <el-icon>
        <Delete />
      </el-icon>
    </span>
  </el-col>
</template>

<script setup name="DraggableItem">
import { ref, defineProps, defineEmits, watch, computed } from "vue";
import draggable from "vuedraggable/dist/vuedraggable.common";
import { typeIdEnum } from "@/utils/articleConfig";
import render from "@/utils/generator/render";
import ImageUpload from "@/components/ImageUpload/index.vue";

const props = defineProps({
  element: Object,
  index: Number,
  drawingList: Array,
  activeId: {
    type: [String, Number],
  },
  formConf: Object,
});

const className = ref("");
const draggableItemRef = ref(null);
const emits = defineEmits(["activeItem", "copyItem", "deleteItem"]);

// 定义组件映射
const componentMap = {
  [typeIdEnum.picture]: ImageUpload,
  [typeIdEnum.topTitle]: ElInput,
  [typeIdEnum.text]: ElInput,
};

// 获取动态组件
const getComponent = (typeId) => {
  return componentMap[typeId] || "render"; // 默认使用 render 组件
};

function activeItem(item) {
  emits("activeItem", item);
}

function copyItem(item, parent) {
  emits("copyItem", item, parent ?? props.drawingList);
}

function deleteItem(item, parent) {
  emits("deleteItem", item, parent ?? props.drawingList);
}

function getComponentData() {
  return {
    gutter: props.element.gutter,
    justify: props.element.justify,
    align: props.element.align,
  };
}

watch(
  () => props.activeId,
  (val) => {
    className.value =
      (props.element.layout === "rowFormItem" ? "drawing-row-item" : "drawing-item") +
      (val === props.element.formId ? " active-from-item" : "");
    if (props.formConf.unFocusedComponentBorder) {
      className.value += " unfocus-bordered";
    }
  },
  { immediate: true }
);
</script>
